package com.ruoyi.common.utils;


import cn.hutool.core.codec.Base64;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.utils.GeneratorUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class OSSUplodFile {
	private static final Logger logger = LoggerFactory.getLogger(OSSUplodFile.class);
    /*阿里云oss上传文件方式*/
    //密匙keyId 可以在阿里云获取到
    public static String accessId="LTAI4GAcKfEGbK6BhZj12QpN";

    //密匙keySecret 可以在阿里云获取到
    public static String accessKey="OHL5ImMJHm1c9qHY7QbcdX70ckiKiV";

    //你的oss所在域，要加http://  不明白可以对照你的文件引用地址
    public static String endpoint="oss-cn-chengdu.aliyuncs.com";

    //你的bucketName 名称  即是你的OSS对象名称 不明白查oss开发文档专业术语
    public static String bucket="gzzsyy";

    private static String dir="image_zsyy/";

    private static String baseUrl="https://file.gzmsdw.cn/";

    private static OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey);

    /**
     * file与bdFile二选其一
     * 如：file不为null，则bdFile必须为null
     * */
    public static Map<String, Object> ossUpload(MultipartFile file,File bdFile) throws Exception {
        ObjectMetadata objectMetadata = new ObjectMetadata();

        //压缩图片
        byte[] than = CompressImgUtil.isThan(file,bdFile);
        String oldPath = "msdwAdmin/uploadPath/static/";
        String wlPath = "msdwAdmin/uploadPath/static/wl.jpg";
        //保存到本地
        File fileEx = new File(oldPath);
        if(!fileEx.exists()){
            fileEx.mkdirs();
        }
        OutputStream os = new FileOutputStream(wlPath);
        os.write(than, 0, than.length);
        os.flush();
        os.close();

        //获取本地图片
        File upFile = new File(wlPath);
        String newFileName= "";

        if(file!=null){
            String fileName = file.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") ).toLowerCase();
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            newFileName = UUID.randomUUID()+fileExt;
        }else {
            objectMetadata.setContentType("image/jpg");
            newFileName = UUID.randomUUID()+".jpg";
        }
        objectMetadata.setContentLength(upFile.length());

        //保存到oss--文件形式
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, dir+newFileName, upFile, objectMetadata);
        ossClient.putObject(putObjectRequest);

        Map<String, Object> data = new HashMap<>();
        data.put("size",upFile.length());

        //删除本地文件
        File deleteFile1 = new File(wlPath);
        deleteFile1.delete();

        data.put("ossUrl", baseUrl + dir + newFileName);
        data.put("url", dir + "/" +newFileName);
        data.put("code", 200);
        data.put("msg", "成功");
        return data;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }


        return "image/jpeg";
    }


    /**
     * 后台通过服务器间接传文件
     * @param file
     * @return
     * @throws IOException
     */
    public static Map<String, Object> createUpload(@RequestParam("file") MultipartFile file) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        String fileName = file.getOriginalFilename();
        String uuid = GeneratorUtil.genFileName();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
//        objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "park/" + date+fileName, file.getInputStream(), objectMetadata);
        PutObjectResult re = ossClient.putObject(putObjectRequest);
        Map<String, Object> data = new HashMap<>();
        data.put("url", baseUrl + "park/" + date+fileName);
        data.put("code", 200);
        data.put("msg", "成功");
        data.put("size", file.getSize());
        return data;
    }

    /**
     * 后台通过服务器间接传文件
     * @param file
     * @return
     * @throws IOException
     */
    public @ResponseBody Map<String, Object> uploadByBase64(String file) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        String uuid = GeneratorUtil.genFileName();
        byte[] decode = Base64.decode(base64Process(file));
//        objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "park/" + uuid+".png", new ByteArrayInputStream(decode), objectMetadata);
        PutObjectResult re = ossClient.putObject(putObjectRequest);
        Map<String, Object> data = new HashMap<>();
        data.put("url", baseUrl + "park/" + uuid +".png");
        data.put("code", 200);
        data.put("msg", "成功");
        return data;
    }

	/**
	 * 后台通过服务器间接传文件
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Object> uploadByFace(String file) throws IOException {
		ObjectMetadata objectMetadata = new ObjectMetadata();
		String uuid = GeneratorUtil.genFileName();
		byte[] decode = Base64.decode(base64Process(file));
//        objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "park/" + uuid+".jpg", new ByteArrayInputStream(decode), objectMetadata);
		PutObjectResult re = ossClient.putObject(putObjectRequest);
		Map<String, Object> data = new HashMap<>();
		data.put("url", baseUrl + "park/" + uuid +".jpg");
		data.put("code", 200);
		data.put("msg", "成功");
		return data;
	}

	//删除文件
	public void deleteFile(@RequestParam("fileName")String fileName){
		OSSClient ossClientDelete = new OSSClient(endpoint, accessId, accessKey);
		String file = fileName.replace("https://ygyxj.oss-cn-shenzhen.aliyuncs.com/","");
		ossClientDelete.deleteObject(bucket, file);
		logger.info(fileName+"删除成功");
		ossClientDelete.shutdown();
	}

	//删除服务器文件
	public void deleteCodeFile(@RequestParam("fileName")String fileName){
		OSSClient ossClientDelete = new OSSClient(endpoint, accessId, accessKey);
		String file = fileName.replace("http://file.gzmsdw.cn/park/","");
		ossClientDelete.deleteObject(bucket, file);
		logger.info(fileName+"删除成功");
		ossClientDelete.shutdown();
	}

	public static String inputUplaod(InputStream input) throws IOException {
		ObjectMetadata objectMetadata = new ObjectMetadata();
//        String uuid = GeneratorUtil.genFileName();
		Long time = System.currentTimeMillis();
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "park/" + time+".jpg", input,objectMetadata);
		PutObjectResult re = ossClient.putObject(putObjectRequest);
		Map<String, Object> data = new HashMap<>();
		data.put("url", baseUrl + "park/" + time +".jpg");
		data.put("code", 200);
		data.put("msg", "成功");
		return baseUrl + "park/" + time +".jpg";
//        return "服务器错误";
	}

    private static String base64Process(String base64Str) {
        if (!StringUtils.isEmpty(base64Str)) {
            String photoBase64 = base64Str.substring(0, 30).toLowerCase();
            int indexOf = photoBase64.indexOf("base64,");
            if (indexOf > 0) {
                base64Str = base64Str.substring(indexOf + 7);
            }

            return base64Str;
        } else {
            return "";
        }
    }


}
